﻿using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Linq;

namespace OpenWaves.Syndication
{
    [DefaultImplementation(typeof(FeedAggregationService))]
    public interface IFeedAggregationService
    {
        AggregatedSyndicationFeed GetAggregatedFeed(IEnumerable<Url> feedsUrls);
    }

    public class FeedAggregationService : IFeedAggregationService
    {
        private readonly ISyndicationFeedLoader loader;

        public FeedAggregationService() : this(new SyndicationFeedLoader())
        {
        }

        public FeedAggregationService(ISyndicationFeedLoader loader)
        {
            this.loader = loader;
        }

        public AggregatedSyndicationFeed GetAggregatedFeed(IEnumerable<Url> feedsUrls)
        {
            var items = new List<SyndicationItem>();
            var errors = new List<SyndicationFeedLoaderException>();
            foreach (var feedUrl in feedsUrls)
            {
                try
                {
                    var url = feedUrl;
                    var feed = this.loader.LoadFeed(url);

                    items.AddRange(feed.Items);
                }
                catch (SyndicationFeedLoaderException e)
                {
                    errors.Add(e);
                }
            }

            return new AggregatedSyndicationFeed(feedsUrls.ToList(), items, errors);
        }
    }
}